package org.erepublik.company.service;

import java.util.ArrayList;
import java.util.Arrays;

import org.erepublik.company.ECountry;
import org.erepublik.company.comparators.ProductComparatorByPriceInGold;
import org.erepublik.company.product.Ticket;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class JSONTicketService extends JSONProductService<Ticket> implements ITicketService {

    public JSONTicketService() {
        super("ticket");
    }
    
    @Override
    protected Ticket[] getEmptyTable() {
        return new Ticket[0];
    }

    @Override
    protected Ticket[] getProductFromJSONArray(JSONArray jsonArrayWithFood) throws JSONException {
        Ticket[] ticket = JSONTicketService.getTicketFromJSONArray(jsonArrayWithFood).toArray(new Ticket[0]);
        Arrays.sort(ticket, new ProductComparatorByPriceInGold());
        return ticket;
    }
    

    public static ArrayList<Ticket> getTicketFromJSONArray(JSONArray jsonArrayWithFood) throws JSONException {
        ArrayList<Ticket> ticket = new ArrayList<Ticket>();
        for (int i = 0; i < jsonArrayWithFood.length(); i++) {
            ticket.add(  Ticket.getTicketFromJSON( (JSONObject)jsonArrayWithFood.get(i) ) );
        }
        return ticket;
    }

    @Override
    public String getMinutesSinceTicketUpdate() {
        return getMinutesSinceUpdate();
    }

    @Override
    public Ticket[] getTickets(ECountry country, int distance) {
        update();
        if (country==null)
            return filter(allProducts, distance);
        return filter(productMap.get(country), distance);
    }
    
    
    
    

    private Ticket[] filter(Ticket[] tickets, int distance) {
        ArrayList<Ticket> filteredTickets = new ArrayList<Ticket>();
        for (int i=0; i < tickets.length; i++) {
            if (tickets[i].getDistance()>=distance)
                filteredTickets.add(tickets[i]);
        }
        return filteredTickets.toArray(new Ticket[0]);
    }


}
